<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'user';
    /**
     * 是否主动维护时间戳
     *
     * @var bool
     */
    public $timestamps = false;
    
    public function login($account,$passwd){
        if (empty($account)) {
            wxresp(0,'请输入账号');
            return false;
        }
        
        if (empty($passwd)) {
            wxresp(0,'请输入密码');
            return false;
        }
        redisTimeLimit($account);
        $user = $this->select("id")->where(['username'=>$account, 'passwd'=>md5($passwd)])->first();
        if (empty($user)) {
            wxresp(0,'账号或密码错误');
            return false;
        }
        $token = md5($user->id.$account);
        $user->logintoken = $token;
        $user->save();
        setcookie("paysystem_token",$token,time() + 30 * 24 * 3600);
        return true;
    }
    
    public function loginOut(){
        setcookie("paysystem_token",'',-1);
        header('location:?a=login');
    }
    
    public function getUserInfo(){
        global $_W;
        if (isset($_COOKIE['paysystem_token'])) $token = $_COOKIE['paysystem_token'];
        if (empty($token)){
            header("location:?a=login");
            exit;
        }
        $user = $this->where('logintoken',$token)->first()->toArray();
        if(empty($user)){
            if ($_W['isajax']) {
                die(wxresp(-1));
            }else{
                header("location:?a=login");
                exit;
            }
        }
        return $user;
    }
    
}
